﻿namespace test3

open System
open System.Management
open wmi

module util =
    
    ////////////////////////
    // JOB
    ////////////////////////

    exception JobFailure of uint16 * string

    type JobState =
        | New = 2
        | Starting = 3
        | Running = 4
        | Suspended = 5
        | ShuttingDown = 6
        | Completed = 7
        | Terminated = 8
        | Killed = 9
        | Exception = 10
        | Service = 11

    let rec wait_for(jobpath:string) =
        if jobpath<>null then
            let job = new WmiObj(new ManagementObject(jobpath))
            let jobstate = job?JobState
            if jobstate = (uint16 JobState.Running) || jobstate = (uint16 JobState.Starting) then
                System.Threading.Thread.Sleep(1000)
                wait_for(jobpath)
            if jobstate <> (uint16 JobState.Completed) then
                raise (JobFailure(job?ErrorCode, job?Description))
        ()


    ////////////////////////
    // RETURN CODE
    ////////////////////////

    exception APIFailure of uint32

    type ReturnCode = 
        | Completed = 0
        | Started = 4096
        | Failed = 32768
        | AccessDenied = 32769
        | NotSupported = 32770
        | Unknown = 32771
        | Timeout = 32772
        | InvalidParameter = 32773
        | SystemInUse = 32774
        | InvalidState = 32775
        | IncorrectDataType = 32776
        | SystemNotAvailable = 32777
        | OutofMemory = 32778

    let check_ret (ret:uint32) =
        if ret <> (uint32 ReturnCode.Completed) && ret <> (uint32 ReturnCode.Started) then
            raise (APIFailure(ret))
        ()
